package com.relytosoft.mizar.media.host.emqx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.relytosoft.mizar.media.common.constant.MediaMqConstants;
import com.relytosoft.mizar.media.common.emqx.client.MqttOp;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author lj
 * @date 2022/6/15 14:24
 */
@Component
public class BehaviorMqttMessageListener implements com.relytosoft.mizar.media.common.emqx.listener.BehaviorMqttMessageListener {

    public static final Logger log = LoggerFactory.getLogger(BehaviorMqttMessageListener.class);

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        try {
            boolean isConsume = false;
            String mqttMsg = new String(message.getPayload(), StandardCharsets.UTF_8);
            JSONObject jsonObject = JSON.parseObject(mqttMsg);
            String opType = jsonObject.getString("OpType");
            String data = jsonObject.getString("Data");
            //判断topic是否为行为分析任务
            if (topic.equals(MediaMqConstants.BEHAVIOR_TASK_TOPIC)) {
                switch (opType) {
                    //添加行为分析任务
                    case "INSERT_BEHAVIOR_TASK":
                        isConsume = createBehaviorTask(data);
                        break;
                    //删除行为分析任务
                    case "DELETE_BEHAVIOR_TASK":
                        isConsume = stopBehaviorTask(data);
                        break;
                    default:
                        break;
                }
            }
            log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",接收的操作类型：" + opType + "，执行结果：" + isConsume);
        } catch (Exception e) {
            log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",处理发生错误：" + e.getMessage());
        }
    }

    private boolean stopBehaviorTask(String data) {
        //TODO 调用比特大陆接口停止行为分析任务
        return false;
    }

    private boolean createBehaviorTask(String data) {
        //TODO 调用比特大陆接口创建行为分析任务
        JSONObject mqttMsg = new JSONObject();
        mqttMsg.put("OpType", "UPDATE_BEHAVIOR_TASK_ID");
        mqttMsg.put("Data", "比特大陆的任务ID信息");
        MqttOp.publish(MediaMqConstants.BEHAVIOR_DATA_TOPIC, JSON.toJSONString(mqttMsg));
        return false;
    }
}
